/**
 * ReportGear(2011)
 */
package com.reportgear.report.core.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sot.core.util.StringUtils;

/**
 * 
 * URL服务类
 * 
 * @version 1.0 2011-4-5
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since ReportGear 1.0
 */
public class URLServer {
	private static final Logger logger = LoggerFactory.getLogger(URLServer.class.getName());

	/**
	 * Get方式读取服务数据
	 * 
	 * @param serverURL
	 *            服务地址
	 * @param charsetName
	 *            字符集
	 * @return 服务数据
	 */
	public String sendGet(String serverURL, String charsetName) {
		try {
			URL url = new URL(serverURL);
			InputStreamReader isr;

			if (StringUtils.isEmpty(charsetName)) {
				isr = new InputStreamReader(url.openStream());
			} else {
				isr = new InputStreamReader(url.openStream(), charsetName);
			}
			BufferedReader in = new BufferedReader(isr);

			StringBuilder sb = this.readBuffer(in);
			in.close();
			return sb.toString();
		} catch (MalformedURLException e) {
			logger.warn(e.toString());
		} catch (UnsupportedEncodingException e) {
			logger.warn(e.toString());
		} catch (IOException e) {
			logger.warn(e.toString());
		}

		return "";
	}

	private StringBuilder readBuffer(BufferedReader in) throws IOException {
		StringBuilder sb = new StringBuilder();
		String s;
		while ((s = in.readLine()) != null) {
			sb.append(s);
		}
		return sb;
	}

	public String sendPost(String serverURL, String xmlDoc) {
		String result = "";
		try {
			URL httpurl = new URL(serverURL);
			HttpURLConnection httpConn = (HttpURLConnection) httpurl.openConnection();
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			PrintWriter out = new PrintWriter(httpConn.getOutputStream());
			out.print(xmlDoc);
			out.flush();
			out.close();
			BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));

			StringBuilder sb = this.readBuffer(in);
			in.close();

			result = sb.toString();
		} catch (Exception e) {
			logger.warn(e.getMessage());
		}
		
		return result;
	}

	public static void main(String[] args) {
		System.out.println(new URLServer().sendGet(
				"http://localhost/hrms3/SalarySalary/QueryReport/Ajax/GetTemplateByID.ashx?ID=1", "UTF-8"));
	}
}
